﻿using System;
using System.Text;

namespace BReusable
{
	public class RandomKeyGenerator
	{
		public const String AllLetters = "abcdefghijklmnopqrstuvwxyz";
		public const String AllNumbers = "0123456789";
		readonly String _keyLetters;
		readonly String _keyNumbers;
		//int Key_Chars;
		//char[] LettersArray;
		//char[] NumbersArray;

		public  RandomKeyGenerator()
		{
			_keyLetters = AllLetters;
			_keyNumbers = AllNumbers;
		}
		public RandomKeyGenerator(String keyLetters)
		{
			_keyNumbers = AllNumbers;
			_keyLetters = keyLetters;
		}
		public RandomKeyGenerator(String keyLetters,String keyNumbers)
		{
			_keyLetters=keyLetters;
			_keyNumbers=keyNumbers;
		}

		public String Generate(int length)
		{
			var valid = _keyNumbers + _keyLetters;
			var sb = new StringBuilder();
			while (0 < length--)
				sb.Append(valid[RandomNumber(0,valid.Length)]);
			return sb.ToString();
		}
#region Marc Gavel's code
		private static readonly Random Random = new Random();
		private static readonly object SyncLock = new object();
		/// <summary>
		/// From Marc Gravell
		/// http://stackoverflow.com/users/23354/marc-gravell
		/// </summary>
		/// <param name="min"></param>
		/// <param name="max"></param>
		/// <returns></returns>
		public static int RandomNumber(int min, int max)
		{
			lock (SyncLock)
			{ // synchronize
				return Random.Next(min, max);
			}
		}
#endregion


	}
}
